<template>
  <div class="electron-settings-view">
    <div class="settings-header">
      <h2>⚡ Electron桌面应用设置</h2>
      <p>管理RickPan桌面应用的功能和行为设置</p>
    </div>

    <el-tabs v-model="activeTab" class="settings-tabs">
      <!-- 兼容性检测 -->
      <el-tab-pane label="🔧 兼容性检测" name="compatibility">
        <ElectronCompatibilityChecker />
      </el-tab-pane>

      <!-- 桌面功能设置 -->
      <el-tab-pane label="🖥️ 桌面功能" name="desktop">
        <el-card class="settings-card">
          <template #header>
            <h3>桌面应用功能设置</h3>
          </template>

          <el-form :model="desktopSettings" label-width="150px">
            <el-form-item label="开机自启动">
              <el-switch 
                v-model="desktopSettings.autoLaunch"
                @change="updateAutoLaunch"
              />
              <div class="setting-description">
                启用后，RickPan将在系统启动时自动运行
              </div>
            </el-form-item>

            <el-form-item label="最小化到托盘">
              <el-switch 
                v-model="desktopSettings.minimizeToTray"
                @change="updateMinimizeToTray"
              />
              <div class="setting-description">
                点击最小化按钮时隐藏到系统托盘而不是任务栏
              </div>
            </el-form-item>

            <el-form-item label="关闭到托盘">
              <el-switch 
                v-model="desktopSettings.closeToTray"
                @change="updateCloseToTray"
              />
              <div class="setting-description">
                点击关闭按钮时隐藏到系统托盘而不是退出应用
              </div>
            </el-form-item>

            <el-form-item label="系统通知">
              <el-switch 
                v-model="desktopSettings.enableNotifications"
                @change="updateNotifications"
              />
              <div class="setting-description">
                启用文件上传完成、AI任务完成等系统通知
              </div>
            </el-form-item>

            <el-form-item label="全局快捷键">
              <el-switch 
                v-model="desktopSettings.enableGlobalShortcuts"
                @change="updateGlobalShortcuts"
              />
              <div class="setting-description">
                启用全局快捷键：Ctrl+Shift+R显示/隐藏窗口，Ctrl+Shift+U快速上传
              </div>
            </el-form-item>
          </el-form>
        </el-card>
      </el-tab-pane>

      <!-- 文件系统集成 -->
      <el-tab-pane label="📁 文件系统" name="filesystem">
        <el-card class="settings-card">
          <template #header>
            <h3>文件系统集成设置</h3>
          </template>

          <el-form :model="fileSystemSettings" label-width="150px">
            <el-form-item label="拖拽上传">
              <el-switch 
                v-model="fileSystemSettings.enableDragDrop"
                @change="updateDragDrop"
              />
              <div class="setting-description">
                允许从文件管理器拖拽文件到应用窗口进行上传
              </div>
            </el-form-item>

            <el-form-item label="右键菜单集成">
              <el-switch 
                v-model="fileSystemSettings.enableContextMenu"
                @change="updateContextMenu"
                disabled
              />
              <div class="setting-description">
                在系统右键菜单中添加"用RickPan打开"选项（开发中）
              </div>
            </el-form-item>

            <el-form-item label="默认下载位置">
              <div class="download-path-setting">
                <el-input 
                  v-model="fileSystemSettings.downloadPath"
                  readonly
                  placeholder="选择下载文件夹"
                />
                <el-button @click="selectDownloadPath" :loading="selectingPath">
                  选择文件夹
                </el-button>
              </div>
              <div class="setting-description">
                设置文件下载的默认保存位置
              </div>
            </el-form-item>
          </el-form>
        </el-card>
      </el-tab-pane>

      <!-- 性能优化 -->
      <el-tab-pane label="⚡ 性能优化" name="performance">
        <el-card class="settings-card">
          <template #header>
            <h3>性能优化设置</h3>
          </template>

          <el-form :model="performanceSettings" label-width="150px">
            <el-form-item label="硬件加速">
              <el-switch 
                v-model="performanceSettings.enableHardwareAcceleration"
                @change="updateHardwareAcceleration"
              />
              <div class="setting-description">
                启用GPU硬件加速以提升渲染性能（需要重启应用）
              </div>
            </el-form-item>

            <el-form-item label="后台运行">
              <el-switch 
                v-model="performanceSettings.enableBackgroundMode"
                @change="updateBackgroundMode"
              />
              <div class="setting-description">
                允许应用在后台继续运行，处理文件同步等任务
              </div>
            </el-form-item>

            <el-form-item label="内存优化">
              <el-switch 
                v-model="performanceSettings.enableMemoryOptimization"
                @change="updateMemoryOptimization"
              />
              <div class="setting-description">
                启用内存优化，自动清理不必要的缓存数据
              </div>
            </el-form-item>
          </el-form>
        </el-card>
      </el-tab-pane>

      <!-- 自动更新 -->
      <el-tab-pane label="🔄 自动更新" name="updates">
        <el-card class="settings-card">
          <template #header>
            <div class="card-header">
              <h3>自动更新设置</h3>
              <el-button type="primary" @click="checkForUpdates" :loading="checkingUpdates">
                检查更新
              </el-button>
            </div>
          </template>

          <el-form :model="updateSettings" label-width="150px">
            <el-form-item label="自动检查更新">
              <el-switch 
                v-model="updateSettings.autoCheck"
                @change="updateAutoCheck"
              />
              <div class="setting-description">
                启动时自动检查应用更新
              </div>
            </el-form-item>

            <el-form-item label="自动下载更新">
              <el-switch 
                v-model="updateSettings.autoDownload"
                @change="updateAutoDownload"
              />
              <div class="setting-description">
                发现更新时自动下载，手动确认安装
              </div>
            </el-form-item>

            <el-form-item label="更新通知">
              <el-switch 
                v-model="updateSettings.enableNotifications"
                @change="updateUpdateNotifications"
              />
              <div class="setting-description">
                有可用更新时显示系统通知
              </div>
            </el-form-item>
          </el-form>

          <div class="update-info" v-if="updateInfo">
            <h4>当前版本信息</h4>
            <div class="version-info">
              <div class="info-item">
                <span class="label">应用版本:</span>
                <el-tag>{{ updateInfo.currentVersion }}</el-tag>
              </div>
              <div class="info-item">
                <span class="label">更新状态:</span>
                <el-tag :type="updateInfo.hasUpdate ? 'warning' : 'success'">
                  {{ updateInfo.hasUpdate ? '有可用更新' : '已是最新版本' }}
                </el-tag>
              </div>
            </div>
          </div>
        </el-card>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import ElectronCompatibilityChecker from '@/components/electron/ElectronCompatibilityChecker.vue'

// 当前激活的标签页
const activeTab = ref('compatibility')

// 桌面功能设置
const desktopSettings = reactive({
  autoLaunch: false,
  minimizeToTray: true,
  closeToTray: false,
  enableNotifications: true,
  enableGlobalShortcuts: true
})

// 文件系统设置
const fileSystemSettings = reactive({
  enableDragDrop: true,
  enableContextMenu: false,
  downloadPath: ''
})

// 性能设置
const performanceSettings = reactive({
  enableHardwareAcceleration: true,
  enableBackgroundMode: true,
  enableMemoryOptimization: false
})

// 更新设置
const updateSettings = reactive({
  autoCheck: true,
  autoDownload: false,
  enableNotifications: true
})

// 状态
const selectingPath = ref(false)
const checkingUpdates = ref(false)
const updateInfo = ref<any>(null)

// 检测是否为Electron环境
const isElectron = !!(window as any).electronAPI

// 设置更新处理函数
const updateAutoLaunch = (value: boolean) => {
  console.log('更新开机自启动设置:', value)
  ElMessage.success(`开机自启动已${value ? '启用' : '禁用'}`)
}

const updateMinimizeToTray = (value: boolean) => {
  console.log('更新最小化到托盘设置:', value)
  ElMessage.success(`最小化到托盘已${value ? '启用' : '禁用'}`)
}

const updateCloseToTray = (value: boolean) => {
  console.log('更新关闭到托盘设置:', value)
  ElMessage.success(`关闭到托盘已${value ? '启用' : '禁用'}`)
}

const updateNotifications = (value: boolean) => {
  console.log('更新通知设置:', value)
  ElMessage.success(`系统通知已${value ? '启用' : '禁用'}`)
}

const updateGlobalShortcuts = (value: boolean) => {
  console.log('更新全局快捷键设置:', value)
  ElMessage.success(`全局快捷键已${value ? '启用' : '禁用'}`)
}

const updateDragDrop = (value: boolean) => {
  console.log('更新拖拽上传设置:', value)
  ElMessage.success(`拖拽上传已${value ? '启用' : '禁用'}`)
}

const updateContextMenu = (value: boolean) => {
  console.log('更新右键菜单设置:', value)
  ElMessage.success(`右键菜单集成已${value ? '启用' : '禁用'}`)
}

const updateHardwareAcceleration = (value: boolean) => {
  console.log('更新硬件加速设置:', value)
  ElMessage.warning(`硬件加速已${value ? '启用' : '禁用'}，需要重启应用生效`)
}

const updateBackgroundMode = (value: boolean) => {
  console.log('更新后台运行设置:', value)
  ElMessage.success(`后台运行已${value ? '启用' : '禁用'}`)
}

const updateMemoryOptimization = (value: boolean) => {
  console.log('更新内存优化设置:', value)
  ElMessage.success(`内存优化已${value ? '启用' : '禁用'}`)
}

const updateAutoCheck = (value: boolean) => {
  console.log('更新自动检查更新设置:', value)
  ElMessage.success(`自动检查更新已${value ? '启用' : '禁用'}`)
}

const updateAutoDownload = (value: boolean) => {
  console.log('更新自动下载更新设置:', value)
  ElMessage.success(`自动下载更新已${value ? '启用' : '禁用'}`)
}

const updateUpdateNotifications = (value: boolean) => {
  console.log('更新更新通知设置:', value)
  ElMessage.success(`更新通知已${value ? '启用' : '禁用'}`)
}

// 选择下载路径
const selectDownloadPath = async () => {
  if (!isElectron) {
    ElMessage.warning('此功能仅在Electron环境中可用')
    return
  }

  selectingPath.value = true
  
  try {
    const electronAPI = (window as any).electronAPI
    const path = await electronAPI.file.selectFolder()
    
    if (path) {
      fileSystemSettings.downloadPath = path
      ElMessage.success('下载路径设置成功')
    }
  } catch (error) {
    ElMessage.error(`选择路径失败: ${error}`)
  } finally {
    selectingPath.value = false
  }
}

// 检查更新
const checkForUpdates = async () => {
  if (!isElectron) {
    ElMessage.warning('此功能仅在Electron环境中可用')
    return
  }

  checkingUpdates.value = true
  
  try {
    const electronAPI = (window as any).electronAPI
    await electronAPI.updater.checkForUpdates()
    
    // 模拟更新信息
    updateInfo.value = {
      currentVersion: electronAPI.app.getVersion(),
      hasUpdate: false
    }
    
    ElMessage.success('检查更新完成')
  } catch (error) {
    ElMessage.error(`检查更新失败: ${error}`)
  } finally {
    checkingUpdates.value = false
  }
}

// 初始化设置
const initSettings = () => {
  if (isElectron) {
    // 从Electron获取当前设置
    const electronAPI = (window as any).electronAPI
    
    // 设置默认下载路径
    if (electronAPI.env) {
      const platform = electronAPI.env.platform
      if (platform === 'win32') {
        fileSystemSettings.downloadPath = 'C:\\Users\\Downloads'
      } else if (platform === 'darwin') {
        fileSystemSettings.downloadPath = '/Users/Downloads'
      } else {
        fileSystemSettings.downloadPath = '/home/Downloads'
      }
    }
  }
}

// 组件挂载时初始化
onMounted(() => {
  initSettings()
})
</script>

<style scoped>
.electron-settings-view {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.settings-header {
  margin-bottom: 24px;
}

.settings-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
}

.settings-header p {
  margin: 0;
  color: #606266;
}

.settings-tabs {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.settings-card {
  border: none;
  box-shadow: none;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  color: #303133;
}

.setting-description {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
  line-height: 1.4;
}

.download-path-setting {
  display: flex;
  gap: 12px;
  align-items: center;
}

.download-path-setting .el-input {
  flex: 1;
}

.update-info {
  margin-top: 24px;
  padding-top: 24px;
  border-top: 1px solid #EBEEF5;
}

.update-info h4 {
  margin: 0 0 16px 0;
  color: #303133;
}

.version-info {
  display: flex;
  gap: 24px;
  flex-wrap: wrap;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.info-item .label {
  font-weight: 500;
  color: #606266;
}
</style>
